# Dreams have to come true after all
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps
import json
import decimal


class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


class BytesEncoder(json.JSONEncoder):
    def default(self, obj):
        """
        只要检查到了是bytes类型的数据就把它转为str类型
        :param obj:
        :return:
         """
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)


def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    # 此处为自己添加***************
    if data == None:
        data = {
            'message': 'data为空',
            'code': 404
        }
    else:
        if 'message' not in data:
            data = {
                'message': 'OK',
                'data': data,
                'code': 200
            }
    # **************************

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    try:
        dumped = dumps(data, **settings, cls=DecimalEncoder) + "\n"
    except TypeError:
        dumped = dumps(data, **settings, cls=BytesEncoder) + "\n"
    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp
